var tools = require('../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

const datacenter = require(tools.rootPath + 'libs/datacenter');

module.exports = class extends datacenter {
    //处理编辑时的垃圾附件
    async treat_attachment(pk) {
        let data = await model.find("select * from szh_article where itemid=?", [pk]);
        let string = data['thumb'] + data['content'];

        let attachments = await model.select("select * from szh_article_attachment where articleid=?", [pk]);

        const fs = require('fs');
        for (let i = 0; i < attachments.length; i++) {
            let v = attachments[i];
            if (string.indexOf(v['url']) >= 0) continue;

            let file = tools.rootPath + 'public' + v['url'];
            if (!fs.existsSync(file)) continue;
            fs.unlinkSync(file);
            await model.delete("delete from szh_article_attachment where itemid=?", [v['itemid']]);
        }
        return true;
    }
}